package com.mago.tis.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.log4j.Logger;

import com.mago.tis.pojo.Tismct;
import com.mago.tis.service.ITransportService;
import com.mago.tis.serviceImpl.TransportService;
import com.mago.tis.utility.ApplicationConstant;
import com.mago.tis.utility.ApplicationException;
import com.mago.tis.utility.StringUtil;

public class TransportController extends BaseController {
	private static final Logger logger = Logger
			.getLogger(TransportController.class);
	private String filePath;
	private boolean isMultipart;
	private File file;
	private String fullFilePath = null;
	ITransportService transportService = null;

	public TransportController() {
		transportService = new TransportService();
	}

	public void init() {
		// Get the file location where it would be stored.
		filePath = getServletContext().getInitParameter("file-upload");
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("Tranport controller called");

		// Check that we have a file upload request
		isMultipart = FileUpload.isMultipartContent(request);
		String action = request.getParameter(ApplicationConstant.ACTION);
		String excelUpload = null;
		String message = "";
		boolean isReadExcel = false;

		// if (StringUtil.isNullOrEmpty(action)
		// && action.equals(ApplicationConstant.UPLOAD_EXCEL)) {

		// Firstly Save the Excel to the configured location
		if (isMultipart) {
			DefaultFileItemFactory factory = new DefaultFileItemFactory();
			// maximum size that will be stored in memory
			// factory.setSizeThreshold(maxMemSize);

			// Location to save data that is larger than maxMemSize.
			// factory.setRepository(new File("N:\\temp"));

			// Create a new file upload handler
			FileUpload upload = new FileUpload(factory);

			// maximum file size to be uploaded.
			// upload.setSizeMax(maxFileSize);

			try {
				// Parse the request to get file items.
				List fileItems = upload.parseRequest(request);
				// Process the uploaded file items
				Iterator i = fileItems.iterator();
				while (i.hasNext()) {
					FileItem fi = (FileItem) i.next();
					if (fi != null) {

						// Get the uploaded file parameters
						String name = fi.getFieldName();
						String fileName = fi.getName();
						String value = fi.getString();

						// Get the action parameter to understand the type
						// of
						// request
						if (StringUtil.isNullOrEmpty(name)) {
							if (name.equals(ApplicationConstant.ACTION))
								action = value;
							else if (name
									.equals(ApplicationConstant.EXCEL_NAME)) {
								if (StringUtil.isNullOrEmpty(value)) {
									// Write the file
									if (fileName.lastIndexOf("\\") >= 0) {
										fullFilePath = filePath
												+ fileName.substring(fileName
														.lastIndexOf("\\"));
										file = new File(fullFilePath);
									} else {
										fullFilePath = filePath
												+ fileName.substring(fileName
														.lastIndexOf("\\") + 1);
										logger.info("fullpath==" + fullFilePath);
										file = new File(fullFilePath);
									}
									fi.write(file);
									excelUpload = value;
								}
							}
						}
					}
				}
			} catch (Exception ex) {
				logger.error("Excel upload--->", ex);
			}

			// Save the excel data in database
			
			try {
				isReadExcel = transportService.saveExcelData(fullFilePath);
				if (isReadExcel) {
					message = ApplicationConstant.EXCEL_READ_SUCCESSFULL;
					logger.info(message);
					response.sendRedirect(request.getContextPath()+"/pages/jsp/welcome.jsp?message="+message);
				} else {
					message = ApplicationConstant.EXCEL_READ_UNSUCCESSFULL;
					logger.info(message);
					response.sendRedirect(request.getContextPath()+"/pages/jsp/welcome.jsp?message="+message);
				}
			} catch (ApplicationException e) {
				logger.error("Exception in TransportController while Uplaoding Excel");
				response.sendRedirect(request.getContextPath()+"/pages/jsp/welcome.jsp?message="+e);
				//e.printStackTrace();
			}
		}
		if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.FILTER_ON_DATE)) {
			String counter = "";
		} else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.BILL_COMPLETE)) {
			List<Tismct> dataList = null;
			try {
				dataList = transportService.loadBilledData();
			} catch (ApplicationException e) {
				request.setAttribute("message", e);
			}
			request.setAttribute("data", dataList);
			rd = request.getRequestDispatcher("/pages/jsp/billed.jsp");
			rd.forward(request, response);
		} else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.BILL_UNCOMPLETE)) {
			List<Tismct> dataList = null;
			try {
				dataList = transportService.loadMasterData();
			} catch (ApplicationException e) {
				request.setAttribute("message", e);
			}
			request.setAttribute("data", dataList);
			rd = request.getRequestDispatcher("/pages/jsp/master-data.jsp");
			rd.forward(request, response);
		} 
	}
}
